package com.cetc.cloud.kmga.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;


/**
 * 邮件服务管理工具
 * 包括邮件的发送与接受
 *
 * @author xutao
 * @version V1.0 创建时间：2017-08-29 14:17
 *          Copyright 2017 by CETC
 */
public class EmailManager {

    private static Logger LOG = LoggerFactory.getLogger(EmailManager.class);
    public static String senderNick = "网安.大数据团队";   // 发件人昵称

    private Properties props; // 系统属性
    private Session session; // 邮件会话对象
    private MimeMessage mimeMsg; // MIME邮件对象
    private Multipart mp;   // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象


    /**
     * 发件人地址
     */
    private String FROM_EMAIL_DRESS;

    /**
     * 邮件服务器配置信息
     *
     * @param host     邮件服务器
     * @param port     端口 默认25
     * @param nickName 发件人名称
     * @param from     发件人邮箱
     * @param username 发件人邮箱账号
     * @param password 发件人邮箱密码
     */
    public EmailManager(String host, Integer port, String nickName, String from, String username, String password) {
        props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.transport.protocol", "smtp");//使用 STARTTLS安全连接
        if (port == null) {
            port = 25;
        }
        props.put("mail.smtp.port", port);
//        props.setProperty("mail.debug", "true");
        props.put("mail.smtp.auth", "true");
        props.put("username", username);        // 使用验证
        props.put("password", password);        // 使用验证
        if (StringUtils.isNotBlank(nickName)) {
            senderNick = nickName;
        }
        FROM_EMAIL_DRESS = from;
        createSession(props);
    }


    public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
        EmailManager manager = new EmailManager("smtp.163.com", null, null, "diabloxt@163.com", "diabloxt@163.com", "pzxtanlp1314");
        String subject="测试附件发送";
        String content="附件里面有详情";
        String[] fileList=new String[2];
        fileList[0]="E:/监管平台前后端接口规范v0.1.5.docx";
        fileList[1]="E:/邮件服务参数.txt";
        manager.sendMail("diabloxt@163.com","623490319@qq.com,1020429932@qq.com",null,null,subject,content,fileList);
    }


    /**
     * 创建session对象
     *
     * @param props
     */
    public void createSession(Properties props) {
        session = Session.getDefaultInstance(props);
    }

    /**
     * 发送邮件只将带附件的邮件发送给收件人
     *
     * @param from     发件人
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param fileList 附件列表
     * @return
     */
    public boolean sendMail(String from, String[] to, String subject, String content, String[] fileList) {
        return this.sendMail(from, to, null, null, subject, content, fileList);
    }

    /**
     * 发送邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param fileList 附件列表
     * @return
     */
    private boolean sendMail(String[] to, String subject, String content, String[] fileList) {
        return this.sendMail(FROM_EMAIL_DRESS, to, null, null, subject, content, fileList);
    }

    /**
     * 发送邮件邮件发送给收件人
     *
     * @param from    发件人
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     * @return
     */
    public boolean sendMail(String from, String[] to, String subject, String content) {
        return this.sendMail(from, to, null, null, subject, content, null);
    }

    /**
     * 发送邮件
     *
     * @param from     发件人
     * @param to       收件人
     * @param copyto   抄送 人
     * @param bccto    密送人
     * @param subject  主题
     * @param content  内容
     * @param fileList 附件列表
     * @return
     */
    public boolean sendMail(String from, String[] to, String[] copyto, String[] bccto, String subject, String content, String[] fileList) {
        boolean success = true;
        try {
            mimeMsg = new MimeMessage(session);
            mp = new MimeMultipart();

            // 自定义发件人昵称
            String nick = "";
            try {
                nick = javax.mail.internet.MimeUtility.encodeText(senderNick);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                LOG.error("自定义发件人昵称出错", e);
            }
            // 设置发件人
            mimeMsg.setFrom(new InternetAddress(from, nick));
            // 设置收件人
            if (to != null && to.length > 0) {
                String toListStr = getMailList(to);
                mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toListStr));
            }
            // 设置抄送人
            if (copyto != null && copyto.length > 0) {
                String ccListStr = getMailList(copyto);
                mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccListStr));
            }
            // 设置抄送人
            if (bccto != null && bccto.length > 0) {
                String bbcListStr = getMailList(bccto);
                mimeMsg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bbcListStr));
            }
            // 设置主题
            mimeMsg.setSubject(subject);
            // 设置正文
            BodyPart bp = new MimeBodyPart();
            bp.setContent(content, "text/html;charset=utf-8");
            mp.addBodyPart(bp);
            // 设置附件
            if (fileList != null && fileList.length > 0) {
                for (int i = 0; i < fileList.length; i++) {
                    bp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(fileList[i]);
                    bp.setDataHandler(new DataHandler(fds));
                    bp.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
                    mp.addBodyPart(bp);
                }
            }
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            // 发送邮件
            if (props.get("mail.smtp.auth").equals("true")) {
                Transport transport = session.getTransport("smtp");
                transport.connect((String) props.get("mail.smtp.host"), (String) props.get("username"), (String) props.get("password"));
                transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
                transport.close();
            } else {
                Transport.send(mimeMsg);
            }
            LOG.info("邮件发送成功");
        } catch (MessagingException e) {
            success = false;
            LOG.info("邮件发送失败", e);
        } catch (UnsupportedEncodingException e) {
            LOG.info("邮件发送失败", e);
        }
        return success;
    }

    /**
     * 发送邮件
     *
     * @param from    发件人
     * @param to      收件人, 多个Email以英文逗号分隔
     * @param subject 主题
     * @param content 内容
     * @return
     */
    public void sendMail(String from, String to, String subject, String content) throws UnsupportedEncodingException, MessagingException {
         sendMail(from, to, null, null, subject, content, null);
    }

    /**
     * 发送邮件
     *
     * @param to      收件人, 多个Email以英文逗号分隔
     * @param subject 主题
     * @param content 内容
     * @return
     */
    public void sendMail(String to, String subject, String content) throws UnsupportedEncodingException, MessagingException {
         sendMail(FROM_EMAIL_DRESS, to, null, null, subject, content, null);
    }

    /**
     * 发送邮件
     *
     * @param from     发件人
     * @param to       收件人, 多个Email以英文逗号分隔
     * @param cc       抄送, 多个Email以英文逗号分隔
     * @param bcc      密送人, 多个Email以英文逗号分隔
     * @param subject  主题
     * @param content  内容
     * @param fileList 附件列表
     * @return
     */
    public void sendMail(String from, String to, String cc, String bcc, String subject, String content, String[] fileList) throws MessagingException, UnsupportedEncodingException {
            mimeMsg = new MimeMessage(session);
            mp = new MimeMultipart();

            // 自定义发件人昵称
            String nick = "";
            try {
                nick = javax.mail.internet.MimeUtility.encodeText(senderNick);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 设置发件人
            mimeMsg.setFrom(new InternetAddress(from, nick));
            // 设置收件人
            if (StringUtils.isNotBlank(to)) {
                mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            }
            // 设置抄送人
            if (StringUtils.isNotBlank(cc)) {
                mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }

            // 设置密送人
            if (StringUtils.isNotBlank(bcc)) {
                mimeMsg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
            }
            // 设置主题
            mimeMsg.setSubject(subject);
            // 设置正文
            BodyPart bp = new MimeBodyPart();
            bp.setContent(content, "text/html;charset=utf-8");
            mp.addBodyPart(bp);
            // 设置附件
            if (fileList != null && fileList.length > 0) {
                for (int i = 0; i < fileList.length; i++) {
                    bp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(fileList[i]);
                    bp.setDataHandler(new DataHandler(fds));
                    bp.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
                    mp.addBodyPart(bp);
                }
            }
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            // 发送邮件
            if (props.get("mail.smtp.auth").equals("true")) {
                Transport transport = session.getTransport("smtp");
                transport.connect((String) props.get("mail.smtp.host"), (String) props.get("username"), (String) props.get("password"));
                transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
                transport.close();
            } else {
                Transport.send(mimeMsg);
            }
    }

    /**
     * 获取邮件发送的地址
     *
     * @param mailArray
     * @return
     */
    public String getMailList(String[] mailArray) {
        StringBuffer toList = new StringBuffer();
        int length = mailArray.length;
        if (mailArray != null && length < 2) {
            toList.append(mailArray[0]);
        } else {
            for (int i = 0; i < length; i++) {
                toList.append(mailArray[i]);
                if (i != (length - 1)) {
                    toList.append(",");
                }

            }
        }
        return toList.toString();
    }
}
